package com.dev.op.util;


import com.dev.op.VO.LoginInfoVO;
import com.dev.op.config.JWTProperties;
import com.dev.op.entity.User;
import com.dev.op.entity.UserRole;
import io.jsonwebtoken.*;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component
public class JWTUtil {

    @Autowired
    JWTProperties jwtProperties;

    //实际需要挂载用户的全部信息
    public String getJWT(User user, List<UserRole> userRoles){
        JwtBuilder jwtBuilder = Jwts.builder();
        List<String> roles = new ArrayList<>();
        for(UserRole userRole : userRoles){
            roles.add(userRole.getRoleName());
        }
        return jwtBuilder.setHeaderParam("typ", jwtProperties.getType())
                .setHeaderParam("alg", jwtProperties.getAlgorithm().toUpperCase())
                .claim("userid", user.getId())
                .claim("name", user.getName())
                .claim("roles", roles)
                .setSubject(jwtProperties.getSubject())
                .setExpiration(new Date(System.currentTimeMillis() + jwtProperties.getExpireTime() * 1000))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256, jwtProperties.getSignature())
                .compact();
    }

    public User parseJWT(String token){
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJWS = parser.setSigningKey(jwtProperties.getSignature()).parseClaimsJws(token);
        Claims claims = claimsJWS.getBody();
        User user = new User();
        user.setId((String) claims.get("userid"));
        //System.out.println("获得用户id:"+user.getId());
        user.setName((String) claims.get("name"));
        user.setPhoneNumber((String) claims.get("phoneNumber"));
        return user;
    }

    public List<String> getUserRoles(String token){
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJWS = parser.setSigningKey(jwtProperties.getSignature()).parseClaimsJws(token);
        Claims claims = claimsJWS.getBody();
        return (List<String>) claims.get("roles");
    }
}
